package cn.simonfish.carrier.controller;

import cn.simonfish.carrier.common.LoginInfo;
import cn.simonfish.carrier.common.web.SessionKit;
import cn.simonfish.carrier.model.SysOrderItem;
import cn.simonfish.carrier.model.SysSubscribe;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.config.AlipayConfig;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * Created by simon on 2017/9/30.
 */
public class AlipayController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    public void gateway(){
        System.out.println("##############gateway()################");
        renderHtml("OK");
    }

    public void callback() throws UnsupportedEncodingException, AlipayApiException {
        System.out.println("##############callback()################");
        //获取支付宝GET过来反馈信息
        Map<String, String> params = buildMapParams();

        boolean signVerified = AlipaySignature.rsaCheckV2(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(getPara("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(getPara("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(getPara("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            renderHtml("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
        }else {
            renderHtml("验签失败");
        }
    }


    public void return_action() throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝GET过来反馈信息
        Map<String, String> params = buildMapParams();

        boolean signVerified = AlipaySignature.rsaCheckV2(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        logger.info("return_action,signVerified:{}",signVerified);
        signVerified = true;
        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(getPara("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(getPara("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //付款金额
            String total_amount = new String(getPara("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            setAttr("out_trade_no",out_trade_no);
            setAttr("trade_no",trade_no);
            setAttr("total_amount",total_amount);
            renderFreeMarker("template/order/pay_result.html");
        }else {
            renderHtml("验签失败");
        }
    }

    /**
     * 异步通知
     */
    @Before(Tx.class)
    public void notify_action() throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝GET过来反馈信息
        Map<String, String> params = buildMapParams();

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        logger.info("notify_action,signVerified:{}",signVerified);
        signVerified = true;
        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(getPara("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(getPara("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //交易状态
            String trade_status = new String(getPara("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                int result = Db.update("update sys_order set status=1 where order_no = ? and status!=1",out_trade_no);
                if(result ==1){
                    finishPay(out_trade_no);
                }
                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if (trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                int result = Db.update("update sys_order set status=1 where order_no = ? and status!=1",out_trade_no);
                if(result ==1){
                    finishPay(out_trade_no);
                }
                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
            }
            logger.info("success");
            renderText("success");
        }else {
            logger.info("fail");
            renderText("fail");
        }
    }

    /**
     * 处理支付完成
     */
    private void finishPay(String order_no){
        List<SysOrderItem> items = SysOrderItem.dao.find("select * from sys_order_item t where t.order_no=?",order_no);
        for (SysOrderItem item : items) {
            SysSubscribe subscribe = SysSubscribe.dao.findFirst("select * from sys_subscribe where user_id=? and site1=?",
                    item.getInt("user_id"),
                    item.getStr("site1")
            );
            //初始化已授权的网站
            LoginInfo info = SessionKit.getLoginInfo(item.getStr("user_phone"));
            if(info!=null){
                Set<String> sites = new HashSet<>();
                List<SysSubscribe> list = SysSubscribe.dao.find("select * from sys_subscribe s where s.user_id=? and s.expire_time>?",info.getUserId(),new Date());
                for (SysSubscribe ss: list             ) {
                    sites.add(ss.getStr("site1") );
                }
                info.setSites(sites);
            }else {
                logger.info("{} not found in sessionMap.",item.getStr("user_phone"));
            }
            if(subscribe == null){
                subscribe = new SysSubscribe();
                subscribe.set("user_id", item.getStr("user_id"));
                subscribe.set("user_phone", item.getStr("user_phone"));
                subscribe.set("modify_time", new Date());
                subscribe.set("start_time", new Date());
                subscribe.set("user_id", item.getStr("user_id"));
                subscribe.set("site1",item.getStr("site1"));
                subscribe.set("expire_time",new Date(System.currentTimeMillis()+item.getInt("day")*24*3600*1000));
                subscribe.save();
            }else {
                Date expire = subscribe.getDate("expire_time");
                long dayTime = item.getInt("day")*24*3600*1000L;
                Date newExpire = new Date(expire.getTime()+dayTime);
                subscribe.set("expire_time", newExpire);
                subscribe.set("modify_time", new Date());
                subscribe.update();
                logger.info("order_no:{},site:{},expire:{}",order_no,item.getStr("site1"),newExpire);
            }
        }

    }


    private Map<String, String> buildMapParams() throws UnsupportedEncodingException {
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = getParaMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return params;
    }

}
